package com.huika.renrench.control.main.epship.acty;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.main.epship.adap.EnClassifyAdapter;
import com.huika.renrench.control.main.epship.adap.EntrepreneurshipProjectAdapter;
import com.huika.renrench.control.project.activity.ProjectDetailActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.model.AllFilterBean;
import com.huika.renrench.model.CategoryBean;
import com.huika.renrench.model.HotKeyWordBean;
import com.huika.renrench.model.LocalBean;
import com.huika.renrench.support.bean.EnshipProject;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.view.TitleBarHelper;

/**
 * @author chenyuan
 * @date：2015年6月2,下午2:15:30
 * @describe:创业项目activity
 */
public class EntrepreneurshipProjectActivity extends BaseAct implements
		Listener<RequestResult<ArrayList<EnshipProject>>>,
		OnRefreshListener2<ListView>, OnItemClickListener, MyLocationListener {

	/** 全部分类 */
	private LinearLayout areaBusinessClassify;
	/** 全部分类Tv */
	public TextView allTv;
	/** 全部地区 */
	private LinearLayout areaLocation;
	/** 全部地区Tv */
	public TextView areaTv;
	/** 关键字 */
	private LinearLayout areaHotKeyWord;
	/** 学费Tv */
	public TextView feesTv;
	/** 分类列表的全部 */
	private LinearLayout container;
	/** 背景图 */
	private View bgView;
	/** 分类列表 */
	private ListView classify_listview;
	/** 分类列表适配器 */
	private EnClassifyAdapter classifyAdapter;
	/** 列表适配器 */
	private EntrepreneurshipProjectAdapter adapter;
	/** 列表 */
	private PullToRefreshListView enshipLv;
	/** 空数据的布局 */
	private View nullView;
	/** 全部分类数据存储 */
	private ArrayList<HashMap<String, String>> allCategory = new ArrayList<HashMap<String, String>>();
	/** 全部地区数据存储 */
	private ArrayList<HashMap<String, String>> allLocation = new ArrayList<HashMap<String, String>>();
	/** 全部热门关键字数据存储 */
	private ArrayList<HashMap<String, String>> allHotWord = new ArrayList<HashMap<String, String>>();
	/** 全局的分类变量 */
	private String typeName = "";
	private String typeId = "";
	private String areaName = "";
	private String areaId = "";
	private String price = "";
	private String priceId = "";

	private String locationId = "";
	private String locationName = "";
	private String categoryId = "";
	private String categoryName = "";
	private String Keyword = "";
	private String KeywordName = "";

	/** 保存上一次的类型 */
	private String lastTypeId = "";
	private String lastAreaId = "";
	private String lastPriceId = "";

	private String lastLocationId = "";
	private String lastCategoryId = "";
	private String lastKeyword = "";

	private LocationBean locationBean = new LocationBean();
	private GaodeMapHelper gaodeMapHelper;
	/** 所有筛选条件数据 */
	private AllFilterBean allFilterBean;

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		super.initData();

		// startLocation();
		getDataFromNet(locationId, categoryId, Keyword);

	}

	@Override
	public void setRootView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_entrepreneurship_project);
		initTopBar();
		initViews();
		initListener();
		/** 请求分类的网络数据 **/
		// 获取所在地 行业分类 热门关键字数据
		getDataAllFilter();

	}

	// private void startLocation() {
	// showLoadingDialog("定位中");
	// gaodeMapHelper = new GaodeMapHelper(this);
	// gaodeMapHelper.setmLocationListener(this);
	// gaodeMapHelper.start();
	// }

	@Override
	public void onStop() {
		super.onStop();
		if (gaodeMapHelper != null) {
			gaodeMapHelper.stop();
		}
	}

	/**
	 * 获取所在地 行业分类 热门关键字数据
	 */
	public void getDataAllFilter() {
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		getUserId(ajaxParams);
		FormResultRequest<AllFilterBean> getResultRequest = new FormResultRequest<AllFilterBean>(
				"http://192.168.16.219:8082/rrcpro-api/projectService/GetUpProjectParam",
				getAllFilterReq, this,
				new TypeToken<RequestResult<AllFilterBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}

	private Listener<RequestResult<AllFilterBean>> getAllFilterReq = new Listener<RequestResult<AllFilterBean>>() {

		@Override
		public void onResponse(RequestResult<AllFilterBean> result) {
			if (result != null && result.flag == 1) {
				allFilterBean = result.getRs();
			} else {
			}
			dismissLoadingDialog();
		}

	};

	/**
	 * 设置所有热门关键字
	 */
	private void setAllHotKeyWordData() {
		allHotWord.clear();
		allHotWord.addAll(dealAreaHotKey(allFilterBean.getHotKeyWords()));
	}

	private Collection<? extends HashMap<String, String>> dealAreaHotKey(
			List<HotKeyWordBean> hotKeyWords) {

		ArrayList<HashMap<String, String>> finalRs = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < hotKeyWords.size(); i++) {
			HotKeyWordBean hotKeyWordBean = hotKeyWords.get(i);
			HashMap<String, String> finaMap = new HashMap<String, String>();
			finaMap.put("keyWordId", hotKeyWordBean.getIdN() + "");
			finaMap.put("keyWordValue", hotKeyWordBean.getValue());
			finalRs.add(finaMap);
		}
		return finalRs;
	}

	/**
	 * 设置所有行业分类
	 */
	private void setAllBusinessClassifyData() {
		allCategory.clear();
		allCategory.addAll(dealAreaCategory(allFilterBean.getCategorys()));
	}

	private Collection<? extends HashMap<String, String>> dealAreaCategory(
			List<CategoryBean> categoryBeans) {

		ArrayList<HashMap<String, String>> finalRs = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < categoryBeans.size(); i++) {
			CategoryBean categoryBean = categoryBeans.get(i);
			HashMap<String, String> finaMap = new HashMap<String, String>();
			finaMap.put("categoryId", categoryBean.getIdN() + "");
			finaMap.put("categoryValue", categoryBean.getValue());
			finalRs.add(finaMap);
		}
		return finalRs;
	}

	/**
	 * 设置所有所在地分类
	 */
	private void setAllLocationData() {
		allLocation.clear();
		allLocation.addAll(dealAreaLocation(allFilterBean.getLocals()));
	}

	private Collection<? extends HashMap<String, String>> dealAreaLocation(
			List<LocalBean> localBeans) {

		ArrayList<HashMap<String, String>> finalRs = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < localBeans.size(); i++) {
			LocalBean localBean = localBeans.get(i);
			HashMap<String, String> finaMap = new HashMap<String, String>();
			finaMap.put("locationId", localBean.getIdN() + "");
			finaMap.put("locationValue", localBean.getValue());
			finalRs.add(finaMap);
		}
		return finalRs;
	}

	/** 获取列表网络 */
	private void getDataFromNet(String locationId, String categoryId,
			String Keyword) {
		// TODO Auto-generated method stub
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

		// ajaxParams.putCommonTypeParam("userId", "0");
		// getUserId(ajaxParams);

		if (!TextUtils.isEmpty(locationId)) {
			ajaxParams.putCommonTypeParam("locationId", locationId);
		}
		if (!TextUtils.isEmpty(categoryId)) {
			ajaxParams.putCommonTypeParam("categoryId", categoryId);
		}
		if (!TextUtils.isEmpty(Keyword)) {
			ajaxParams.putCommonTypeParam("Keyword", Keyword);
		}

		ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
		ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);

		FormResultRequest<ArrayList<EnshipProject>> getResultRequest = new FormResultRequest<ArrayList<EnshipProject>>(
				"http://192.168.16.219:8082/rrcpro-api/projectService/GetProjects",
				this, this,
				new TypeToken<RequestResult<ArrayList<EnshipProject>>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		getResultRequest.setRetryPolicy(new DefaultRetryPolicy(30 * 1000, 1,
				1.0f));
		executeRequest(getResultRequest);
	}

	private void getUserId(JSONWrapAjaxParams ajaxParams) {
		String u_id = GlobalApp.getInstance().getUserId();
		if (!TextUtils.isEmpty(u_id)) {
			ajaxParams.putCommonTypeParam("userId", u_id);
		} else {
			ajaxParams.putCommonTypeParam("userId", "0");
		}
	}

	/**
	 * @author cy
	 * @date 2015年6月2日,上午11:32:34
	 */
	private void initTopBar() {
		// TODO Auto-generated method stub
		TitleBarHelper titleBarHelper = new TitleBarHelper(this,
				R.string.common_null, R.string.common_null,
				R.string.common_null);
		titleBarHelper.setTitleMsg("创业项目");
		titleBarHelper.setLeftMsg("创业");
		titleBarHelper.setRightImg(R.drawable.index_search_icon);
		titleBarHelper.setOnRightImgClickListener(this);
	}

	/**
	 * @author cy
	 * @date 2015年6月2日,上午11:32:20
	 */
	private void initListener() {
		// TODO Auto-generated method stub
		areaBusinessClassify.setOnClickListener(this);
		areaLocation.setOnClickListener(this);
		areaHotKeyWord.setOnClickListener(this);
		bgView.setOnClickListener(this);

		classify_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				int realPos = position
						- ((ListView) parent).getHeaderViewsCount();
				if (realPos >= 0 && realPos < classifyAdapter.getCount()) {
					HashMap<String, String> map = classifyAdapter
							.getItem(realPos);

					String keyWordId = map.get("keyWordId");
					String categoryId = map.get("categoryId");
					String locationId = map.get("locationId");
					locationName = map.get("locationValue");
					categoryName = map.get("categoryValue");
					KeywordName = map.get("keyWordValue");

					setClassifyName(categoryName, locationName, KeywordName);
					setMenu();

					/*** 保存已经选中的类型 */
					if (!TextUtils.isEmpty(keyWordId)) {
						lastKeyword = keyWordId;
					}
					if (!TextUtils.isEmpty(categoryId)) {
						lastCategoryId = categoryId;
					}
					if (!TextUtils.isEmpty(locationId)) {
						lastLocationId = locationId;
					}

					// 选择上面分类目标的任意一个后，当前页数改为1；modify by zc 2015-7-15
					CURRENT_PAGE = 1;
					Log.i("test", lastLocationId + ":" + lastCategoryId + ":"
							+ lastKeyword);
					// getDataFromNet(typeId, areaId, priceId,
					// "",locationBean.latitude,locationBean.longtitude);
					getDataFromNet(lastLocationId, lastCategoryId, lastKeyword);
				}
			}
		});
	}

	/**
	 * @author cy
	 * @date 2015年6月3日,上午9:03:32
	 * @param typeName
	 * @param areaName
	 * @param price
	 */
	protected void setClassifyName(String typeName, String areaName,
			String price) {
		// TODO Auto-generated method stub
		if (!TextUtils.isEmpty(typeName)) {
			allTv.setText(typeName);
		}
		if (!TextUtils.isEmpty(areaName)) {
			areaTv.setText(areaName);
		}
		if (!TextUtils.isEmpty(price)) {
			feesTv.setText(price);
		}
	}

	/**
	 * @author cy
	 * @date 2015年6月2日,上午11:32:16
	 */
	private void initViews() {
		// TODO Auto-generated method stub
		nullView = findViewById(R.id.null_layout);
		areaBusinessClassify = (LinearLayout) findViewById(R.id.business_classify_ll);
		allTv = (TextView) findViewById(R.id.allTv);
		areaLocation = (LinearLayout) findViewById(R.id.location_ll);
		areaTv = (TextView) findViewById(R.id.areaTv);
		areaHotKeyWord = (LinearLayout) findViewById(R.id.hot_key_word_ll);
		feesTv = (TextView) findViewById(R.id.feesTv);
		container = (LinearLayout) findViewById(R.id.one_pingou_lv_container);
		bgView = findViewById(R.id.one_pingou_lv_bg);
		// serch_right = (ImageView) findViewById(R.id.serch_right);
		classify_listview = (ListView) findViewById(R.id.classify_listview);
		classifyAdapter = new EnClassifyAdapter(this);
		classify_listview.setAdapter(classifyAdapter);

		/** 列表 */
		enshipLv = (PullToRefreshListView) findViewById(R.id.enshipLv);
		adapter = new EntrepreneurshipProjectAdapter(this);
		enshipLv.setAdapter(adapter);
		enshipLv.setOnRefreshListener(this);
		enshipLv.setOnItemClickListener(this);

	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.business_classify_ll:
			// initTestClassify();
			// setAllClassifyData(allDatas);
			setAllBusinessClassifyData();
			classifyAdapter.setGroup(allCategory);
			setTabSelect(true, false, false);
			setMenu();
			break;
		case R.id.location_ll:
			// initTestClassify2();
			setAllLocationData();
			classifyAdapter.setGroup(allLocation);
			setTabSelect(false, true, false);
			setMenu();
			break;
		case R.id.hot_key_word_ll:
			// if (!allFees.isEmpty()) {
			// allFees.clear();
			// }
			// classifyAdapter.setGroup(allFees);
			setAllHotKeyWordData();
			classifyAdapter.setGroup(allHotWord);
			setTabSelect(false, false, true);
			setMenu();
			break;

		case R.id.one_pingou_lv_bg:
			setMenu();
			break;
		case R.id.title_right_iv:
			Intent intent = new Intent(this, SerchProject.class);
			intent.putExtra("", "");
			showActivity(this, intent);
			break;

		default:
			break;
		}
	}

	private void setMenu() {
		if (View.GONE == container.getVisibility()) {
			container.setVisibility(View.VISIBLE);
		} else {
			container.setVisibility(View.GONE);
			setTabSelect(false, false, false);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		int realPos = position - ((ListView) parent).getHeaderViewsCount();
		if (realPos >= 0 && realPos < adapter.getCount()) {
			EnshipProject addressBean = (EnshipProject) adapter
					.getItem(realPos);

			// Intent show = new Intent(this, EnProjectDetailActivity.class);
			// show.putExtra(EnProjectDetailActivity.PROJECT_TAG, addressBean);
			// startActivity(show);
			Intent intent=new Intent(this,ProjectDetailActivity.class);
			intent.putExtra("pid", addressBean.idN);
			startActivity(intent);
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> arg0) {
		// TODO Auto-generated method stub
		CURRENT_PAGE = 1;
		getDataFromNet(lastLocationId, lastCategoryId, lastKeyword);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> arg0) {
		// TODO Auto-generated method stub
		CURRENT_PAGE++;
		getDataFromNet(lastLocationId, lastCategoryId, lastKeyword);
	}

	@Override
	public void onResponse(RequestResult<ArrayList<EnshipProject>> result) {
		// TODO Auto-generated method stub
		enshipLv.onRefreshComplete();
		if (result.flag == 1) {
			if (result != null && result.getRs() != null
					&& result.getRs().size() > 0) {
				setNullView(false);
				setListData(result.getRs());
				changeRefreshMode(result.getTotalSize());
				Log.d("chenyuan", result.getRs() + "");
			} else {
				setNullView(true);
			}
		} else {
			// showToastMsg(result.msg);
		}
		// if (mOverlayLayout!=null) {
		// hideOverLay();
		// }
		dismissLoadingDialog();
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		// TODO Auto-generated method stub
		super.onErrorResponse(error);
		enshipLv.onRefreshComplete();
		dismissLoadingDialog();
	}

	/***
	 * 设置请求回来的列表网络数据
	 * 
	 * @author cy
	 * @date 下午3:17:26
	 */
	private void setListData(ArrayList<EnshipProject> rs) {
		if (CURRENT_PAGE == 1) {
			adapter.setGroup(rs);
		} else {
			adapter.addItems(rs);
		}
		// enshipLv.setAdapter(adapter);
	}

	private void setNullView(boolean isShow) {
		if (isShow) {
			enshipLv.setVisibility(View.GONE);
			nullView.setVisibility(View.VISIBLE);
		} else {
			enshipLv.setVisibility(View.VISIBLE);
			nullView.setVisibility(View.GONE);
		}
	}

	/***
	 * 改变刷新模式
	 * 
	 * @author cy
	 * @date 上午10:06:55
	 * @param totalSize
	 */
	private void changeRefreshMode(int totalSize) {
		if (totalSize > CURRENT_PAGE) {
			enshipLv.setMode(Mode.BOTH);
		} else {
			enshipLv.setMode(Mode.PULL_FROM_START);
		}
	}

	private void setTabSelect(boolean isSelectAll, boolean isSelectArea,
			boolean isSelectFee) {
		areaBusinessClassify.setSelected(isSelectAll);
		areaLocation.setSelected(isSelectArea);
		areaHotKeyWord.setSelected(isSelectFee);
	}

	@Override
	public void onLocation(LocationBean locationBean) {
		// TODO Auto-generated method stub
		dismissLoadingDialog();
		if (!TextUtils.isEmpty(locationBean.province)) {
			// showToastMsg("定位成功！");
			Log.d("location", "EntrepreneurshipProjectActivity创业项目列表定位成功");
			Log.d("cy", "进度：+" + locationBean.latitude + "维度:"
					+ locationBean.longtitude);
			// getDataFromNet(typeId, areaId, price, "", locationBean.latitude
			// + "", locationBean.longtitude + "");

			getDataFromNet(locationId, categoryId, Keyword);
			this.locationBean = locationBean;

			GlobalApp.getInstance().setLocated(true);
		} else {
			showToastMsg("定位失败！");
			// getDataFromNet(typeId, areaId, price, "", "", "");
			GlobalApp.getInstance().setLocated(false);
		}
		if (gaodeMapHelper != null) {
			gaodeMapHelper.stop();
		}
	}

}
